<!--
 * @Description: 
 * @Author: jun.wu
 * @Date: 2022-10-18 15:10:12
 * @LastEditors: jun.wu
 * @LastEditTime: 2022-11-14 11:14:06
-->
<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- <h2>员工</h2> -->
      <page-tools :show-before="true">
        <!-- 左侧显示总记录 -->
        <template v-slot:before>
          <span slot="before">共{{ page.total }}条数据</span>
        </template>
        <!-- 右侧显示按钮 -->
        <template v-slot:after>
          <span slot="after">
            <el-button
              size="small"
              type="warning"
              @click="$router.push('/import')"
              >execl导入
            </el-button>
            <el-button size="small" type="danger" @click="exportData"
              >execl导出
            </el-button>
            <el-button size="small" type="primary" @click="showDialog = true"
              >新增员工
            </el-button>
          </span>
        </template>
      </page-tools>
      <!-- 表格组件 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <!-- sortable可排序 -->
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column width="120px" label="头像" align="center">
            <!-- 放置插槽 -->
            <!-- <template slot-scope="{row}" ></template> -->
            <template v-slot="{ row }">
              <img
                v-imageerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                @click="showQrCode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <!-- 作用域插槽+过滤器处理入职时间 -->
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="{ row }">
              <el-switch :value="row.enableState === 1"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)"
                >角色</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="deleteEmployee(row.id)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>
    <!-- 放置组件弹窗 -->
    <!-- sync修饰符 子组件改变父组件的语法糖 -->
    <AddEmployee :showDialog.sync="showDialog" />
    <el-dialog title="二维码" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 放置分配组件 -->
    <AssignRole
      ref="assignRole"
      :showRoleDialog.sync="showRoleDialog"
      :userId="userId"
    />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from "@/api/employees";
import EmployeeEnum from "@/api/constant/employees";
import AddEmployee from "./components/add-employee.vue";
import AssignRole from "./components/assign-role.vue";
import QrCode from "qrcode";

export default {
  components: {
    AddEmployee,
    AssignRole,
  },
  data() {
    return {
      list: [], // 接数据的
      page: {
        page: 1, // 当前页码
        size: 10,
        total: 0, // 总数
      },
      loading: false, //显示遮罩层
      showDialog: false,
      formData: {
        username: "",
        mobile: "",
        formOfEmployment: "",
        workNumber: "",
        departmentName: "",
        timeOfEntry: "",
        correctionTime: "",
      },
      showCodeDialog: false, //显示二维码弹层
      showRoleDialog: false,
      userId: null,
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.page);
      this.page.total = total;
      this.list = rows;
      this.loading = false;
    },
    changePage(newPage) {
      this.page.page = newPage;
      this.getEmployeeList();
    },
    //格式化聘用形式的数据
    formatEmployment(row, column, cellValue, index) {
      //要去找cellValue对应的值
      const obj = EmployeeEnum.hireType.find((item) => item.id === cellValue);
      return obj ? obj.value : "未知";
    },
    //员工删除
    async deleteEmployee(id) {
      try {
        await this.$confirm("确定删除该员工吗？");
        //点击确定会进入下方
        await delEmployee(id);
        this.getEmployeeList();
        this.$message.success("删除成功");
      } catch (error) {
        console.log(error);
      }
    },
    //exexl导出(懒加载)
    exportData() {
      const headers = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      import("@/vendor/Export2Excel").then(async (excel) => {
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total,
        });
        const data = this.formatJson(headers, rows);
        const multiHeader = [["姓名", "主要信息", "", "", "", "", "部门"]];
        const merges = ["A1:A2", "B1:F1", "G1:G2"];
        excel.export_json_to_excel({
          header: Object.keys(headers), //表头 必填
          data, //具体数据 必填
          filename: "员工信息表", //非必填
          autoWidth: true, //非必填
          bookType: "xlsx", //非必填
        });
      });
    },
    formatJson(headers, rows) {
      return rows.map((item) => {
        return Object.keys(headers).map((key) => {
          //判断字段
          // if (
          //   headers[key] == "timeOfEntry" ||
          //   headers[key] == "correctionTime"
          // ) {
          // }else if(headers[key] == "formOfEmployment"){}
          return item[headers[key]];
        });
      });

      // return rows.map((item) =>
      //   Object.keys(headers).map((key) => item[headers[key]])
      // );
    },
    showQrCode(url) {
      if (url) {
        this.showCodeDialog = true;
        //nextTick可以在上一次数据更新完毕，页面渲染完毕之后执行
        this.$nextTick(() => {
          //此时可以确认已经有ref对象
          QrCode.toCanvas(this.$refs.myCanvas, url); //将地址转化成二维码
        });
      } else {
        this.$message.warning("该用户还未上传头像");
      }
    },
    async editRole(id) {
      this.userId = id;
      await this.$refs.assignRole.getUserDetailById(id);
      //异步方法 强制使用async来使异步方法完成后再打开弹层
      //弹出弹窗
      this.showRoleDialog = true;
    },
  },
};
</script>

<style></style>
